package cn.ihoway.impl;

import cn.ihoway.dao.AllocationDao;
import cn.ihoway.dao.RoomDao;
import cn.ihoway.entity.Allocation;
import cn.ihoway.entity.Room;
import cn.ihoway.service.RoomService;
import cn.ihoway.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

public class RoomServiceImpl implements RoomService {

    private final SqlSession sqlSession = MybatisUtils.getSqlSession();
    private final RoomDao roomDao = sqlSession.getMapper(RoomDao.class);
    private final AllocationDao allocationDao = sqlSession.getMapper(AllocationDao.class);

    /**
     * 1、创建房间 2、房主加入房间
     */
    @Override
    public int create(Room room,Allocation allocation){
        //创建房间
        int rs = roomDao.insertSelective(room);
        //房主加入房间
        int rs2 = allocationDao.insertSelective(allocation);
        if(rs > 0 && rs2 > 0){
            sqlSession.commit();
        }else {
            sqlSession.rollback();
        }
        return rs * rs2;
    }

    /**
     * 玩家加入房间
     * 1、更新房间信息 2、玩家加入房间
     */
    @Override
    public int joinRoom(Room room,Allocation allocation){
        //更新房间
        int rs = roomDao.updateByPrimaryKeySelective(room);
        int rs2 = allocationDao.insertSelective(allocation);
        if(rs > 0 && rs2 > 0){
            sqlSession.commit();
        }else {
            sqlSession.rollback();
        }
        return rs * rs2;
    }

    /**
     * 玩家退出房间
     * 1、更新房间信息 2、删除玩家信息
     */
    @Override
    public int exitRoom(Room room,Integer id){
        int rs = roomDao.updateByPrimaryKeySelective(room);
        int rs2 = allocationDao.deleteByPrimaryKey(id);
        if(rs > 0 && rs2 > 0){
            sqlSession.commit();
        }else {
            sqlSession.rollback();
        }
        return rs * rs2;
    }

    /**
     * 通过房间id查询房间信息
     */
    @Override
    public Room search(String id){
        return roomDao.selectByPrimaryKey(id);
    }

    @Override
    public int update(Room room){
        int rs = roomDao.updateByPrimaryKeySelective(room);
        if(rs > 0){
            sqlSession.commit();
        }else {
            sqlSession.rollback();
        }
        return rs;
    }

}
